Having visually traced how the stack handles the expression `{[()]}` using the FILO principle, we now formalize this into a runnable algorithm.

  • Processing Openers: If the character is an opening delimiter ((, [, {), we immediately push it onto the stack. This reserves it for a future match.
  • Processing Closers: If the character is a closing delimiter (), ], }), we must check the stack.
    • If the stack is empty (Underflow), the expression is immediately unbalanced.
    • Otherwise, we pop the top element and check if it correctly matches the current closing delimiter. A mismatch renders the expression unbalanced.
  • Final Validation: After iterating through the entire input string, the expression is balanced only if the stack is completely empty. If any opening delimiters remain, they were never closed.

Conditions for Unbalanced Brackets

An expression is determined to be unbalanced if any of these three conditions occur:

  • Underflow: A closing bracket (e.g., `)`) is found, but the stack is empty, meaning there was no corresponding opening bracket.
  • Mismatch: A closing bracket is found, but the item at the top of the stack is not its matching opening bracket (e.g., finding `}` when `[` is on top).
  • Incomplete: The end of the expression is reached, but the stack is not empty, meaning some opening brackets were never closed.